package com.rr.sort;

import java.util.Arrays;

/**
 * @author RR
 * @date 2022/10/1 23:48
 */
public class QuickSort {
    public static void main(String[] args) {
        int[] array = new int[]{5, 10, 7, 6, 3, 2, 8};
        quickSort(array, 0, array.length - 1);
        System.out.println(Arrays.toString(array));
    }

    public static void quickSort(int[] array, int left, int right) {
        if (left < right) {
            int split = split(array, left, right);
            quickSort(array, left, split - 1);
            quickSort(array, split + 1, right);
        }
    }

    public static int split(int[] array, int left, int right) {
        int middle = array[right]; // 选最右边，做为分割数组的中间数
        int l = left;
        // 从左边开始遍历，将小于等于middle的放到左边
        for (int i = left;  i< right; i++) {
            if (array[i] <= middle) {
                int temp = array[i];
                array[i] = array[l];
                array[l] = temp;
                l++;
            }
        }
        // 将middle放到中间位置，分割成左右两数组
        int temp = array[l];
        array[l] = middle;
        array[right] = temp;
        return l;
    }

}
